﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Models.ConfigManager;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Application.AppConfigureManage;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;

namespace Zocono.WCS.Admin.Controllers.ConfigManageMoudle
{
    public class PlcWriteDBController : BaseController
    {
        private readonly PlcWriteDbInfoApp _plcWriteDbInfoApp;
        private readonly PlcConnectionInfoApp _plcConnectionInfoApp;

        public PlcWriteDBController(PlcWriteDbInfoApp plcWriteDbInfoApp,  PlcConnectionInfoApp plcConnectionInfoApp, IMemoryCache memoryCache, TracesApp tracesApp, IHttpContextAccessor httpContextAccessor) : base(memoryCache, tracesApp, httpContextAccessor)
        {
            this._plcWriteDbInfoApp = plcWriteDbInfoApp;
            this._plcConnectionInfoApp = plcConnectionInfoApp;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 封装用于下拉列表的数据
        /// </summary>
        /// <returns></returns>
        public async Task<PlcWriteDbSearchPageData> GetPlcSearchDataAsync()
        {
            var plcPageSearchData = new PlcWriteDbSearchPageData();
            //通过 IP 去搜索
            var plcIps = await _plcConnectionInfoApp.GetPlcConnectionInfoAsync();
            plcPageSearchData.PlcIpSearchs = new List<PlcIPSearchPageData>();
            if (plcIps != null && plcIps.Count > 0)
            {
                foreach (var plcIp in plcIps)
                {
                    plcPageSearchData.PlcIpSearchs.Add(new PlcIPSearchPageData() { PlcConnectId = plcIp.ID.ToString(), PlcConnectIp = plcIp.IP });
                }
            }
            return plcPageSearchData;
        }

        /// <summary>
        /// plc写入DB 配置页面
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> PlcWriteDBInfoAsync()
        {
            var pageWriteData = await GetPlcSearchDataAsync();
            //await AddTracesInfo();
            return View(pageWriteData);
        }

        /// <summary>
        /// 获取plc写入DB配置列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetAllPlcWriteDBInfoAsync()
        {
            var where = new QueryPlcWriteDbInfoDto();
            where.PageIndex = (Start / Length) + 1;
            where.PageSize = Length;
            where.EquipmentCode = Request.Form["equipmentCode"].ToString();
            //where.PlcConnectionId = Request.Form["PlcConnectionId"].ToInt64();
            where.ObjectType = Request.Form["objectType"].ToString();
            where.DbCode = Request.Form["DBCode"].ToInt32()==0?null: Request.Form["DBCode"].ToInt32();
            where.PlcConnectionId = Request.Form["ipSearch"].ToInt64();
            var plcWriteList = await _plcWriteDbInfoApp.GetPlcWriteDbInfoAsync(where);
            //处理cpuType名称显示
            foreach (var plcWrite in plcWriteList.Result)
            {
                var result = plcWrite.PlcCpuType.ToString();
                var item = S7CpuTypeItem.S7CpuTypeDatasource.FirstOrDefault(c => c.CpuTypeValue == plcWrite.PlcCpuType.ToInt32());
                if (item != null)
                {
                    result = item.CpuTypeName;
                }
                plcWrite.PlcCpuTypeName = result;
            }
            var pageData = new TableData<PlcWriteDbInfoDto>(Draw, plcWriteList.Total, plcWriteList.Total, plcWriteList.Result);

            //await AddTracesInfo(5, 0, "获取PLCWriteDB数据列表");

            return Json(pageData);
        }



        public async Task<JsonResult> DelPlcWriteDBInfoAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                result = await _plcWriteDbInfoApp.DeletePlcWriteDbInfoAsync(id);
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
                {
                result = false;
                msg = e.Message;
            }
            await AddTracesInfo(4, 0, "删除PLC写入DB配置");
            return CreateJsonGetResult(result, msg);
                }



        public async Task<ActionResult> PlcWriteDbInfoAddOrEditAsync(long id)
        {
            var pageData = await GetPlcSearchDataAsync();
            if (id > 0)
            {
                var plcWriteInfoData = await _plcWriteDbInfoApp.GetPlcWriteDbInfoByIDAsync(id);
                pageData.ID = plcWriteInfoData.ID;
                pageData.DbCode = plcWriteInfoData.DbCode;
                pageData.DbStart = plcWriteInfoData.DbStart;
                pageData.EquipmentCode = plcWriteInfoData.EquipmentCode;
                pageData.ObjectType = plcWriteInfoData.ObjectType;
                pageData.PlcConnectionId = plcWriteInfoData.PlcConnectionId;
            }

            return View(pageData);
        }

        public async Task<JsonResult> OperatePlcWriteDBInfoAsync()
        {
            var plcReadDbInfoDto = new PlcWriteDbInfoDto();
            plcReadDbInfoDto.ID = Request.Form["id"].ToInt64();
            plcReadDbInfoDto.EquipmentCode = Request.Form["EquipmentCode"].ToString();
            plcReadDbInfoDto.DbCode = Request.Form["DbCode"].ToInt32();
            plcReadDbInfoDto.DbStart = Request.Form["DbStart"].ToInt32();
            plcReadDbInfoDto.ObjectType = Request.Form["ObjectType"].ToString();
            plcReadDbInfoDto.PlcConnectionId = Request.Form["PlcConnectionId"].ToInt64();

            bool result;
            string msg;
            try
            {
                if (plcReadDbInfoDto.ID == 0)
                {
                    var res = await _plcWriteDbInfoApp.AddPlcWriteDbInfoAsync(plcReadDbInfoDto);
                    await AddTracesInfo(2, 0, "新增PLC读取DB配置");
                    result = res > 0;
                }
                else
                {
                    result = await _plcWriteDbInfoApp.UpdatePlcWriteDbInfoAsync(plcReadDbInfoDto);
                    await AddTracesInfo(3, 0, "修改PLC读取DB配置");
                }
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }

            return CreateJsonGetResult(result, msg);
        }

        //public async Task<JsonResult> DelPlcWriteDBInfoAsync()
        //{
        //    var id = Request.Form["id"].ToInt64();
        //    bool result;
        //    string msg;
        //    try
        //    {
        //        result = await _plcWriteDbInfoApp.DeletePlcWriteDbInfoAsync(id);
        //        msg = result ? "成功" : "失败";
        //    }
        //    catch (Exception e)
        //    {
        //        result = false;
        //        msg = e.Message;
        //    }
        //    await AddTracesInfo(4, 0, "PLC写入DB配置删除");
        //    return CreateJsonGetResult(result, msg);
        //}
    }
}
